/**
 * http://gold.ncfdc.com.cn/Default.aspx?tname=251\main
 * 南昌领航房产信息爬虫
 * sunny/acc 2017-06-20
 */

const utils = require("../../utils");
import { Base, Item } from "../base";

class TempClass {
    name: string;
    url: string;
}

class ncfdc_spider extends Base {
    tmps: TempClass[];
    currentPageContent: string;

    constructor() {
        super();
        this.name = "南昌领航房产信息";
        this.encode = "utf-8";
        this.tmps = [];
        this.debug = false;
        this.timeout = 1000000;
        this.collection = "ncfdcxxext";
    }

    getPageCount(): number {
        var self = this;
        var content: string = this.spider.getSync("http://gold.ncfdc.com.cn/Default.aspx?tname=251\\main");
        var $: CheerioSelector = this.cheerio.load(content);
        var cnt: number = 0;
        $("div.lpda_pinyin a").each(function (index, ele) {
            cnt++;
            var url: string = $(ele).attr("href");
            var name: string = $(ele).text().trim();
            var item: TempClass = new TempClass();
            item.name = name;
            item.url = url;
            self.tmps.push(item);
        });
        return cnt;
    }

    getItems(pageIndex: number): Item[] {
        var result: Item[] = [];
        var item: TempClass = this.tmps[pageIndex];
        var url: string = "http://gold.ncfdc.com.cn/" + item.url;
        var content: string = this.spider.getSync(url);
        // console.log(content);
        console.log(url);
        var mainItem: Item = this.buildItem("ncfdcxx");
        mainItem.source = this.name;
        mainItem.title = item.name;
        result.push(mainItem);
        var $: CheerioSelector = this.cheerio.load(content);
        (mainItem as any)["项目地址"] = $("#ctl20_ADDRESS").text().trim();
        var kfs = $("#ctl20_developer_name").text().trim();
        (mainItem as any)["开发商"] = kfs;
        (mainItem as any)["项目情况"] = $(".pading_10").eq(0).text().trim();
        $(".doc_xq_TABLE tr").each(function (index, ele) {
            var key = $(ele).find("td").eq(0).text().trim();
            key = key.substr(0, key.length - 1);
            var value = $(ele).find("td").eq(1).text().trim();
            (mainItem as any)[key] = value;
        });
        $(".doc_710tb tr").each(function (index, ele) {
            var key = $(ele).find("td").eq(0).text().trim();
            key = key.substr(0, key.length - 1);
            var value = $(ele).find("td").eq(1).text().trim();
            (mainItem as any)[key] = value;
        });
        //楼盘基本情况
        var tds_2 = $(".doc_710tb").find("tr").eq(0).find("td");
        (mainItem as any)["物业类型"] = tds_2.eq(1).text().trim();
        (mainItem as any)["行政区"] = tds_2.eq(3).text().trim();
        (mainItem as any)["建筑面积"] = tds_2.eq(5).text().trim();
        
        var tds_3 = $(".doc_710tb").find("tr").eq(1).find("td");
        (mainItem as any)["緑地率"] = tds_3.eq(1).text().trim();
        (mainItem as any)["临近地铁"] = tds_3.eq(3).text().trim();
        (mainItem as any)["容积率"] = tds_3.eq(5).text().trim();

        var tds_4 = $(".doc_710tb").find("tr").eq(2).find("td");
        (mainItem as any)["物业费"] = tds_4.eq(1).text().trim();

        var tds_5 = $(".doc_710tb").find("tr").eq(3).find("td");
        (mainItem as any)["车位"] = tds_5.eq(1).text().trim();

        var tds = $(".doc_xq_jbqkTABLE tr").eq(1).find("td");
        (mainItem as any)["首次预售"] = tds.eq(0).text().trim();
        (mainItem as any)["最近预售"] = tds.eq(1).text().trim();
        (mainItem as any)["预售总栋数"] = tds.eq(2).text().trim();
        (mainItem as any)["30日住宅均价"] = tds.eq(3).text().trim();
        (mainItem as any)["30日非住宅均价"] = tds.eq(4).text().trim();
        (mainItem as any)["累计成交套数"] = tds.eq(5).text().trim();
        (mainItem as any)["累计成交面积"] = tds.eq(6).text().trim();
        (mainItem as any)["当前可售套数"] = tds.eq(7).text().trim();
        (mainItem as any)["当前可售面积"] = tds.eq(8).text().trim();
        (mainItem as any)["url"] = url;
        // var suburl = $(".doc_xq_xsxx_A3").attr("href").trim();
        // if (suburl) {
        //     this.processList(mainItem.title, suburl, kfs, result);
        // }
        var hrefId: string = "";
        if (/hrefID=(\d+)/.test(url)) {
            hrefId = RegExp.$1;
        }
        var suburl = "http://www.ncfdc.com.cn:5060/?tname=62\\DisplayB_xm&hrefID=" + hrefId;
        // console.log(suburl);
        this.processDetail(suburl, mainItem);
        return result;
    }

    private processDetail(url: string, item: Item): Item {
        let content = this.spider.getSync(url);
        let $ = this.cheerio.load(content);
        $(".za_xm_TABLE2").eq(1).find("tr").each(function (index, ele) {
            var e = $(ele);
            var cols = e.find("td");
            var key = cols.eq(0).text().trim();
            if (/【(.*?)】/.test(key)) {
                key = RegExp.$1;
            }
            var value = cols.eq(1).text().trim();
            (item as any)[key] = value;
            key = cols.eq(2).text().trim();
            if (/【(.*?)】/.test(key)) {
                key = RegExp.$1;
            }
            value = cols.eq(3).text().trim();
            (item as any)[key] = value;
        });
        return item;
    }

    // 获取房管局信息
    private processList(title: string, suburl: string, kfs: string, items: Item[]): void {
        var content = this.spider.getSync(suburl);
        this.currentPageContent = content;
        var $ = this.cheerio.load(content);
        var pgCount: number = 1;
        pgCount = parseInt($("#ctl16_grdSeatList_ctl23_lblPageCount").text().trim());
        for (var i = 1; i <= pgCount; i++) {
            this.processPage(i, title, suburl, kfs, items);
        }
    }

    // 获取某页的信息
    private processPage(pageIndex: number, title: string, suburl: string, kfs: string, items: Item[]): void {
        if (pageIndex == 1) {
            // 当页码为1的时候，直接使用，不需要跳转
        } else {
            var form: any = {};
            var $ = this.cheerio.load(this.currentPageContent);
            $("#form1 input[type='hidden']").each(function (index, ele) {
                var e = $(ele);
                var v = e.attr("value");
                var n = e.attr("name");
                if (v) {
                    form[n] = v;
                }
                form["__EVENTTARGET"] = "ctl16$grdSeatList$ctl14$cmdPreview";
                form["__EVENTARGUMENT"] = "";
                form["__VIEWSTATEENCRYPTED"] = "";
                form["ctl16$txtSearch"] = "";
            });
            this.currentPageContent = this.spider.postSync(suburl, form); // POST跳转方式F
        }
        var $ = this.cheerio.load(this.currentPageContent);
        var trs = $("#ctl16_grdSeatList tr");
        var trslength = trs.length;
        var self = this;
        trs.each(function (index, ele) {
            if (index > 1 && (index < trslength - 1)) { // 忽略前2行
                var ref = $(ele);
                var ldname = ref.find("td").eq(0).text().trim(); // 楼栋名称
                var ysxkz = ref.find("td").eq(1).text().trim(); // 预售证号
                var fzrq = ref.find("td").eq(2).text().trim(); // 发证日期
                var _url = ref.find("td").eq(8).find("a").attr("href");
                self.processItems(title, ldname, ysxkz, fzrq, _url, kfs, items);
            }
        });
    }

    // 获取最后一级的明细数据
    private processItems(title: string, ldname: string, ysxkz: string, ysrq: string, url: string, kfs: string, items: Item[]): void {
        var content = this.spider.getSync(url);
        var $ = this.cheerio.load(content);
        var self = this;
        $("table.fk_TABLE").each(function (index, ele) {
            var dyh = $(ele).find("tr").eq(2).text().trim(); //单元号
            $(ele).find("tr").each(function (i, el) {
                if (i > 3) {
                    var _item = $(el);
                    var tds = _item.find("td");
                    var outItem = self.buildItem();
                    outItem.source = self.name;
                    (<any>outItem)["所在楼层"] = tds.eq(0).text().trim();
                    var fh = tds.eq(1).text().trim();
                    (<any>outItem)["房号"] = fh;
                    (<any>outItem)["户型"] = tds.eq(2).text().trim();
                    (<any>outItem)["建筑面积"] = tds.eq(3).text().trim();
                    (<any>outItem)["套内面积"] = tds.eq(4).text().trim();
                    (<any>outItem)["公摊面积"] = tds.eq(5).text().trim();
                    (<any>outItem)["销售状态"] = tds.eq(6).text().trim();
                    (<any>outItem)["朝向"] = tds.eq(7).text().trim();
                    (<any>outItem)["销售参考单价"] = tds.eq(8).text().trim();
                    (<any>outItem)["开发商"] = kfs;
                    (<any>outItem)["楼栋名称"] = ldname;
                    (<any>outItem)["预售许可证"] = ysxkz;
                    (<any>outItem)["发证日期"] = ysrq;
                    (<any>outItem)["项目名称"] = title;
                    var t = dyh + " " + fh; // 新的标题
                    t = t.replace(/\n/g, "");
                    t = t.replace(/\r/g, "");
                    t = t.replace("                    ", " ");
                    outItem.title = t;
                    items.push(outItem);
                }
            });
        });
    };
}

export = new ncfdc_spider();